
// gen一个随机数值串出来
function genRandCode (leng) {
  if (String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
  else {
    throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
  }
}
// gen一个随机字母串出来
function genRandEngCode (leng) {
  let result = ''
  let i = 0
  const tempArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  if (String(typeof leng).toLocaleLowerCase() === 'number') {
    while (i < leng) {
      let randomNum = ~~(Math.random() * 26)
      result += tempArr[randomNum]
      i++
    }
    return result
  } else {
    throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
  }
}
/**
 * 截取指定长度的数值字符串
 * @param {string|number} num 要截取的数字基础
 * @param {number} leng 截取长度
 * @return {string} 返回指定长度的数值字符串
 */
function addPreZero (num, leng) {
  let tempStr = ''
  let i = 0
  while (i < leng) {
    tempStr += '0'
    i++
  }
  return (`${tempStr}${num}`).slice(-leng)
}

/**
 * 组装符合后端要求的数据结构并parse为表单项进行表单提交
 * @param {HTMLElement} _this 触发当前函数的HTML元素
 * @param {number} nameBase 根据后端要求，数组是以数字为键，客户要求为6， 按揭要求是7
 * @param {string} formID 要进行提交的form表单id，将按照id选取元素进行序列化后做进一步处理
 */
function postThisSubPage (_this, nameBase, formID) {
  let formValue = []
  let formAction = $(`#${formID}`).attr('action')
  let tempNameArr = []
  let tempValueObj = {}
  let tempForm = `<form autocomplete="off" method='post' action='${formAction}' id='tempGenForm'></form>`
  let tempInput = ``
  let PreValue = JSON.parse('[]')
  try {
    PreValue = JSON.parse(sessionStorage.getItem('nextPingu'))
  } catch (err) {
    console.log(`解析数据发生错误：`)
    console.log(sessionStorage.getItem('nextPingu'))
    $.toptip('历史数据解析发生错误，请联系工作人员', 'error')
    throw new Error(err)
  }
  for (let item of PreValue) {
    tempInput += `<input type='hidden' name='${item.name}' value='${item.value}'>`
  }
  if (String(nameBase) === '9') {
    formValue = [
      [
        // {
        //   zhengxin_check_count_method: '',
        //   zhengxin_check_count_cycle: '',
        //   zhengxin_check_count_time: ''
        // }
      ],
      [
        // {
        //   yuqi_check_count_cycle: '',
        //   yuqi_check_count_method: '',// 累计
        //   yuqi_check_count_time: '',
        //   yuqi_check_count_source: ''
        // }
      ]
    ]
    // 9 是特殊情况，需要数组套数组
    /**
     * // 征信
     * $arr[9][0]=array(
     *   0=>array(
     *     //'zhengxin_check_if'=>'',
     *     'zhengxin_check_count_method'=>'信用卡查询',
     *     'zhengxin_check_count_cycle'=>'2',
     *     'zhengxin_check_count_time'=>'9'
     *   ),
     *   1=>array(
     *    // 'zhengxin_check_if'=>'',
     *     'zhengxin_check_count_method'=>'信用卡查询',
     *     'zhengxin_check_count_cycle'=>'3',
     *     'zhengxin_check_count_time'=>'1'
     *   ),
     *   1=>array(
     *     //'zhengxin_check_if'=>'',
     *     'zhengxin_check_count_method'=>'信用卡查询',
     *     'zhengxin_check_count_cycle'=>'6',
     *     'zhengxin_check_count_time'=>'6'
     *   ),
     * )
     * // 逾期
     * $arr[9][1]=array(...)
     */
    /** 首先是征信数据处理，name 处理为形如 [0][n][zhengxin_check_count_method] */
    // 判断是否需要提交，判断点击和按钮是否多余0
    const count = $('#zhengxin_popup .tag_wrap input:checked').length
    let zhengxinMethod = []
    if (count > 0) {
      // 循环多选按钮
      $(`.zhengxin_block .tag_container [name='zhengxin_fliter']`).each((index, item) => {
        zhengxinMethod.push($(item).val())
      })
      zhengxinMethod = zhengxinMethod.join(',')
      // 循环每一个fliter行
      $('.zhengxin_block .fliter_line').each((index, item) => {
        const cycle = $(item).find(`input[name='zhengxin_check_count_cycle']`).attr('inori-data-code')
        const time = $(item).find(`input[name='zhengxin_check_count_time']`).attr('inori-data-code')
        formValue[0][index] = {}
        formValue[0][index].zhengxin_check_count_method = zhengxinMethod
        formValue[0][index].zhengxin_check_count_cycle = cycle
        formValue[0][index].zhengxin_check_count_time = time
      })
    }
    /** 然后是逾期数据处理，name 处理为形如 [1][n][yuqi_check_count_cycle] */
    $('.yuqi_block .fliter_line').each((index, item) => {
      const cycle = $(item).find(`input[name='yuqi_check_count_cycle']`).attr('inori-data-code')
      const time = $(item).find(`input[name='yuqi_check_count_time']`).attr('inori-data-code')
      const source = $(item).find(`input[name='yuqi_check_count_source']`).attr('inori-data-code')
      formValue[1][index] = {}
      formValue[1][index].yuqi_check_count_cycle = cycle
      formValue[1][index].yuqi_check_count_method = '累计'
      formValue[1][index].yuqi_check_count_time = time
      formValue[1][index].yuqi_check_count_source = source
    })
    // 生成模板内容
    // for (let item of Object.keys(tempValueObj)) {
    //   let value = tempValueObj[item]
    //   let name = item
    //   tempInput += `<input type='hidden' name='${nameBase}${name}' value='${value}'>`
    // }
    $.each(formValue, (zhengxinOryuqi, dataArray) => {
      $.each(dataArray, (index, dataObject) => {
        $.each(dataObject, (name, value) => {
          tempInput += `<input type='hidden' name='${nameBase}[${zhengxinOryuqi}][${index}][${name}]' value='${value}'>`
        })
      })
    })
  } else {
    formValue = $(`#${formID}`).serializeArray()
    $.each(formValue, (index, item) => {
      if (tempNameArr.indexOf(item.name) === -1) {
        tempNameArr.push(item.name)
        tempValueObj[item.name] = `${item.value}`
      } else {
        tempValueObj[item.name] += `,${item.value}`
      }
    })
    for (let item of Object.keys(tempValueObj)) {
      let value = tempValueObj[item]
      let name = item
      tempInput += `<input type='hidden' name='${nameBase}[${name}]' value='${value}'>`
    }
  }

  // 提交之前刷新一次session
  sessionStorage.setItem('currentFilter', 'null')
  window.top.postMessage({formData: tempForm.replace('></form>', `>${tempInput}</form>`)}, '*')
  // // console.log(`${tempInput}`)
  // if ($('#tempGenForm')) $('#tempGenForm').remove()
  // $('body').append(tempForm)
  // $('#tempGenForm').append(tempInput)
  // // throw new Error('debug')
  // $('#tempGenForm').submit()
}

function postOrder (evt) {
  $.toptip('正在重组数据', 'success')
  let PreValue = JSON.parse('[]')
  let value = $(evt.target).text().charCodeAt(0) === 59045 ? 1 : 0
  let formAction = $(`#order_query`).val()
  let tempForm = `<form autocomplete="off" method='post' action='${formAction}' id='tempGenForm'></form>`
  let tempInput = ``
  let sessionValue = evt.data.type === 'lx' ? (() => {
    return $('#lixi_sort').text().charCodeAt(0) === 59045 ? [1, 0] : [0, 0]
  })() : (() => {
    return $('#edu_sort').text().charCodeAt(0) === 59045 ? [0, 1] : [0, 0]
  })()
  try {
    PreValue = JSON.parse(sessionStorage.getItem('nextPingu'))
  } catch (err) {
    console.log(`解析数据发生错误：`)
    console.log(sessionStorage.getItem('nextPingu'))
    $.toptip('历史数据解析发生错误，请联系工作人员', 'error')
    throw new Error(err)
  }
  sessionStorage.setItem('lastProduct_sort_arr', JSON.stringify(sessionValue))
  for (let item of PreValue) {
    tempInput += `<input type='hidden' name='${item.name}' value='${item.value}'>`
  }

  tempInput += `<input type='hidden' name='5[0]' value='${value}'>`
  tempInput += `<input type='hidden' name='5[1]' value='${evt.data.type}'>`

  // if ($('#tempGenForm')) $('#tempGenForm').remove()
  // $('body').append(tempForm)
  // $('#tempGenForm').append(tempInput)
  // throw new Error('debug')
  $.toptip('正在发送请求', 'success')
  window.top.postMessage({formData: tempForm.replace('></form>', `>${tempInput}</form>`)}, '*')
  // $('#tempGenForm').submit()
}

// 生成uid
$('.pro_uid').each((index, item) => {
  let leng = 5
  let rawID = ''
  if ($(item).attr('inori-data')) rawID = $(item).attr('inori-data').replace(/\D/g, '')
  else {
    return
  }
  let resultID = ''
  const rawIDAlt = addPreZero(rawID, leng)
  resultID = `A${genRandEngCode(1)}${genRandCode(1)}${rawIDAlt.substr(0, 4)}${genRandCode(2)}${rawIDAlt.substr(-1)}`
  $(item).text(resultID)
  sessionStorage.setItem(`pro_id${rawID}`, resultID)
  // console.log(rawID)
})

/**
 * 发送后端一个ajax请求
 * @param {event} evt 点击事件
 */
// function postThisQudaoID (evt) {
//   let qudaoID = $(evt.target).attr('qudao-id')
//   let urlEleID = ''
//   let ajaxMethod = ''
//   let urlBase = ''
//   if (evt.data) {
//     urlEleID = evt.data.urlEleID || 'add_qudao_to_chat_room'
//     ajaxMethod = evt.data.method || 'post'
//   }
//   urlBase = $(`#${urlEleID}`).val() === '' ? (() => { throw new Error(`ajax 取值为空`) })() : String($(`#${urlEleID}`).val())
//   console.log(`发送ajax请求，地址： ${urlBase}，数据：{qudaoID: ${qudaoID}}， method：${ajaxMethod}`)
//   $.ajax(urlBase, {
//     method: ajaxMethod,
//     data: {qudaoID: qudaoID}
//   }).done((data) => {
//     console.log('接收数据：')
//     console.log(data)
//   }).fail((err) => {
//     console.log('返回错误：')
//     console.log(err)
//   })
// }

// 监听聊天按钮点击
// $('.contact_button').on({click: postThisQudaoID}, {urlEleID: '', method: 'post'})
// 监听列表按钮点击
$('.pro_adv .weui-btn_mini').each((index, item) => {
  $(item).on('touchstart', (evt) => {
    evt.preventDefault()
    evt.stopPropagation()
    const eleID = $(evt.target).attr('for')
    if ($(`#${eleID}`).prop('checked') && $(evt.target).attr('confirmed') === 'true') {
      // 已经激活，需要关闭本页并移除本active
      $(`#${eleID}`).prop('checked', false).change()
      $(evt.target).removeClass('active')
    } else {
      // 未激活
      // 筛选列表地下渠道是否已经在聊天室
      const from_user_group_id = sessionStorage.getItem('from_user_group_id')
      if (from_user_group_id === null || from_user_group_id === 'null') {
        // 激活本页并移除其他active
        $(`#${eleID}`).prop('checked', true).change()
        $(`.pro_adv .weui-btn_mini`).each((index, item) => {
          if($(item).hasClass('active')) $(item).removeClass('active')
        })
        $(evt.target).addClass('active')
        return
      } else if ($(evt.target).attr('confirmed') === 'true') {
        // 激活本页并移除其他active
        $(`#${eleID}`).prop('checked', true).change()
        $(`.pro_adv .weui-btn_mini`).each((index, item) => {
          if($(item).hasClass('active')) $(item).removeClass('active')
        })
        $(evt.target).addClass('active')
        return
      } else {
        // 正在筛选,不做任何事情直接返回
        if ($(evt.target).attr('confirmed') === 'doing') return
        // 进行筛选
        $(evt.target).attr('confirmed', 'doing')
        const ajaxIfURL = String($('#ajax_jud').val())
        const roomID = String($('#chat_person_id').val())
        // 筛选promise数组
        let checkPromiseArr = []
        const targetContainerEle = $(`#${$(evt.target).attr('for')}`).closest('.pro_qudao')
        $.each(targetContainerEle.find(`.contact_button[goods-id][qudao-id]`), (index, item) => {
          if ($(item).attr('checking') === 'done') {
            return
          }
          const qudaoID = String($(item).attr('qudao-id'))
          const goodsID = String($(item).attr('goods-id'))
          const ajaxAddData = {
            chat_id: roomID,
            goods_id: goodsID,
            y_id: qudaoID
          }
          // 待筛选按钮
          checkPromiseArr.push(new Promise( (resolve, reject) => {
            $.ajax(ajaxIfURL, {
              method: 'post',
              data: ajaxAddData,
              beforeSend: () => {
                $(item).attr('checking', 'true')
              }
            }).fail((err) => {
              resolve()
              $(item).attr('checking', 'done')
            }).done((res) => {
              resolve()
              $(item).attr('checking', 'done')
              if (String(res.code) === '1') {
                $(item).text('正在互动')
                $(item).removeAttr('onclick')
                $(item).off('click')
                $(item).on('click', (evt) => {
                  $.toptip(`该渠道已经在留言板了`, 'warning')
                  evt.preventDefault()
                })
              }
            })
          } ))
        })
        if (checkPromiseArr.length === 0) {
          // 检查对象长度为0
          $(evt.target).attr('confirmed', 'true')
          // 激活本页并移除其他active
          $(`#${eleID}`).prop('checked', true).change()
          $(`.pro_adv .weui-btn_mini`).each((index, item) => {
            if($(item).hasClass('active')) $(item).removeClass('active')
          })
          $(evt.target).addClass('active')
          return
        }
        $.toptip('正在查询渠道情况，列表即将渲染。请稍候。。。', 900, 'success')
        Promise.all(checkPromiseArr).then( _ => {
          $(evt.target).attr('confirmed', 'true')
          // 激活本页并移除其他active
          $(`#${eleID}`).prop('checked', true).change()
          $(`.pro_adv .weui-btn_mini`).each((index, item) => {
            if($(item).hasClass('active')) $(item).removeClass('active')
          })
          $(evt.target).addClass('active')
        }).catch(err => {
          $(evt.target).attr('confirmed', 'true')
          // 激活本页并移除其他active
          $(`#${eleID}`).prop('checked', true).change()
          $(`.pro_adv .weui-btn_mini`).each((index, item) => {
            if($(item).hasClass('active')) $(item).removeClass('active')
          })
          $(evt.target).addClass('active')
        })
      }
    }
  })
})

// 修改并列出"客户要求"区域的title对应nama
$(document).ready(() => {
  $('.tag_title[inori-title-data]').each((index, item) => {
    let titleDataArr = $(item).attr('inori-title-data').split(',')
    let title = titleDataArr[0]
    let titleName = titleDataArr[1]
    $(item).text(title.replace(/标签/, '').replace(/维度/, '').replace(/纬度/, ''))
    $(item).closest('.weui_cells').find('input').each((index, item) => {
      $(item).attr('name', titleName)
    })
  })
  // 监听排序
  $('#lixi_sort').on({click: postOrder}, {type: 'lx'})
  $('#edu_sort').on({click: postOrder}, {type: 'ed'})

  // 如果存在筛选条件，那么添加一个重置按钮
  if (sessionStorage.getItem('currentFilter')) {
    try {
      const filter = JSON.parse(sessionStorage.getItem('currentFilter'))
      // if (filter.length > 6) {
      //   // 长度大于6代表是有筛选操作
      //   $('.js-loadmore span').text(`重置`)
      //   $('.js-loadmore').one('click', evt => {
      //     $('#lixi_sort').click()
      //   })
      // }
      let shouldHaveReaset = false
      $.each(filter, (index, item) => {
        // 大于6代表是有筛选操作
        if(Number.parseInt(item.name.substr(0,1)) >= 6) {
          shouldHaveReaset = true
        }
      })
      if (shouldHaveReaset) {
        const templ = `
          <div class="weui-loadmore weui-loadmore_line js-loadmore">
            <!-- 跟随body背景色 -->
            <span class="weui-loadmore__tips" style='background-color:#eaeff5;'>点我重置条件</span>
          </div>
        `
        $('#rewriteTag_container').after(templ)
        let reFliting = false
        $('.js-loadmore').on('click', evt => {
          if (reFliting) {
            $.toptip('正在重组数据', 'success')
            evt.preventDefault()
            return
          }
          // $('#lixi_sort').click()
          $.toptip('正在重组数据', 'success')
          reFliting = true
          let PreValue = JSON.parse('[]')
          let formAction = $(`#order_query`).val()
          let tempForm = `<form autocomplete="off" method='post' action='${formAction}' id='tempGenForm'></form>`
          let tempInput = ``
          try {
            PreValue = JSON.parse(sessionStorage.getItem('nextPingu'))
          } catch (err) {
            console.log(`解析数据发生错误：`)
            console.log(sessionStorage.getItem('nextPingu'))
            $.toptip('历史数据解析发生错误，请联系工作人员', 'error')
            throw new Error(err)
          }
          for (let item of PreValue) {
            tempInput += `<input type='hidden' name='${item.name}' value='${item.value}'>`
          }

          // if ($('#tempGenForm')) $('#tempGenForm').remove()
          // $('body').append(tempForm)
          // $('#tempGenForm').append(tempInput)
          // throw new Error('debug')
          sessionStorage.setItem('lastProduct_sort_arr', `[0, 0]`)
          $.toptip('正在发送请求', 'success')
          window.top.postMessage({formData: tempForm.replace('></form>', `>${tempInput}</form>`)}, '*')
          reFliting = false
        })
      }
    } catch (e) {
      // 解析失败
      console.groupCollapsed(`${new Date} 解析筛选数据失败`)
      console.error(e)
      console.groupEnd()
    }
  }
})
// 初始化征信查询卡片查询
let mouthArray = Array(36)
let mouthViewArray = Array(36)
let countTimeArray = Array(20)
let countTimeViewArray = Array(20)
$.each(mouthArray, (index, item) => {
  mouthArray[index] = index + 1
  if (index < 35) mouthViewArray[index] = `${index + 1}个`
  else mouthViewArray[index] = `${index + 1}个`
})
$.each(countTimeArray, (index, item) => {
  countTimeArray[index] = index + 1
  if (index < 19) countTimeViewArray[index] = `${index + 1}次`
  else countTimeViewArray[index] = `${index + 1}次或以上`
})

$('.zhengxin_check_count_cycle_wrap input').picker({
  title: "计算周期",
  cols: [
    {
      textAlign: 'center',
      values: mouthArray,
      displayValues: mouthViewArray
    }
  ],
  onChange: (picker, values, displayValues) => {
    picker.input.attr('inori-data-code', values[0])
    setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
  }
})
$(".zhengxin_check_count_cycle_wrap input").picker("open")
$(".zhengxin_check_count_cycle_wrap input").picker("close")

$('.zhengxin_check_count_time_wrap input').picker({
  title: "不超过",
  cols: [
    {
      textAlign: 'center',
      values: countTimeArray,
      displayValues: countTimeViewArray
    }
  ],
  onChange: (picker, values, displayValues) => {
    picker.input.attr('inori-data-code', values[0])
    setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
  }
})
$(".zhengxin_check_count_time_wrap input").picker("open")
$(".zhengxin_check_count_time_wrap input").picker("close")

// 初始化逾期查询卡片查询
// 变量定义
/** 12 */
let yuqiCheckCountCycleArray = Array(12)
/** 12 */
let yuqiCheckCountCycleViewArray = Array(12)
/** 10 */
let yuqiCheckCountTimeArray = Array(10)
/** 10个或以上 */
let yuqiCheckCountTimeViewArray = Array(10)
/** 12 */
let yuqiCheckCountSourceArray = Array(12)
/** 12 */
let yuqiCheckCountSourceViewArray = Array(12)
$.each(yuqiCheckCountCycleArray, (index, item) => {
  yuqiCheckCountCycleArray[index] = index + 1
  if (index < 11) yuqiCheckCountCycleViewArray[index] = `${index + 1}个`
  else yuqiCheckCountCycleViewArray[index] = `${index + 1}个`
})
$.each(yuqiCheckCountTimeArray, (index, item) => {
  yuqiCheckCountTimeArray[index] = index + 1
  if (index < 9) yuqiCheckCountTimeViewArray[index] = `${index + 1}个`
  else yuqiCheckCountTimeViewArray[index] = `${index + 1}个或以上`
})
$.each(yuqiCheckCountSourceArray, (index, item) => {
  yuqiCheckCountSourceArray[index] = index + 1
  if (index < 11) yuqiCheckCountSourceViewArray[index] = `${index + 1}`
  else yuqiCheckCountSourceViewArray[index] = `${index + 1}`
})
// 全局挂载
window.zhengxinDataArray = {
  mouthArray: mouthArray,
  mouthViewArray: mouthViewArray,
  countTimeArray: countTimeArray,
  countTimeViewArray: countTimeViewArray,
  yuqiCheckCountCycleArray: yuqiCheckCountCycleArray,
  yuqiCheckCountCycleViewArray: yuqiCheckCountCycleViewArray,
  yuqiCheckCountTimeArray: yuqiCheckCountTimeArray,
  yuqiCheckCountTimeViewArray: yuqiCheckCountTimeViewArray,
  yuqiCheckCountSourceArray: yuqiCheckCountSourceArray,
  yuqiCheckCountSourceViewArray: yuqiCheckCountSourceViewArray
}
$('.yuqi_check_count_cycle_wrap input').picker({
  title: "N个月",
  cols: [
    {
      textAlign: 'center',
      values: yuqiCheckCountCycleArray,
      displayValues: yuqiCheckCountCycleViewArray
    }
  ],
  onChange: (picker, values, displayValues) => {
    picker.input.attr('inori-data-code', values[0])
    setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
  }
})
$(".yuqi_check_count_cycle_wrap input").picker("open")
$(".yuqi_check_count_cycle_wrap input").picker("close")

$('.yuqi_check_count_time_wrap input').picker({
  title: "N个",
  cols: [
    {
      textAlign: 'center',
      values: yuqiCheckCountTimeArray,
      displayValues: yuqiCheckCountTimeViewArray
    }
  ],
  onChange: (picker, values, displayValues) => {
    picker.input.attr('inori-data-code', values[0])
    setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
  }
})
$(".yuqi_check_count_time_wrap input").picker("open")
$(".yuqi_check_count_time_wrap input").picker("close")

$('.yuqi_check_count_source_wrap input').picker({
  title: "N",
  cols: [
    {
      textAlign: 'center',
      values: yuqiCheckCountSourceArray,
      displayValues: yuqiCheckCountSourceViewArray
    }
  ],
  onChange: (picker, values, displayValues) => {
    picker.input.attr('inori-data-code', values[0])
    setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
  }
})
$(".yuqi_check_count_source_wrap input").picker("open")
$(".yuqi_check_count_source_wrap input").picker("close")

// 只有选了才会有
$('#zhengxin_popup .tag_wrap input').on('change', (evt) => {
  const count = $('#zhengxin_popup .tag_wrap input:checked').length
  if (count > 0) {
    $(evt.target).closest('.weui_cells').find('.fliter_line').each((index, item) => {
      $(item).css('display', 'flex')
    })
  } else {
    $(evt.target).closest('.weui_cells').find('.fliter_line').each((index, item) => {
      $(item).css('display', 'none')
    })
  }
})
// 开局click一下，隐藏
$('#zhengxin_popup .tag_wrap input:eq(0)').change()
// 动态添加征信筛选条件
$('#click_to_add_zhengxin').on('click', (evt) => {
  const parentEle = $(evt.target).closest('.fliter_line')
  const imgURL = parentEle.attr('imgurl')
  // 自增才能下一步
  const countNum = Number(parentEle.attr('inori-count')) + 1
  if (countNum > 7) {
    $.toptip(`每类条件最多可以添加7条`)
    throw new Error(`每类条件最多可以添加7条`)
  }
  parentEle.attr('inori-count', countNum)
  const templ = `
    <div class="fliter_line">
      <div class="zhengxin_check_count_cycle_wrap"><input form='hidden_form_shaixuan' type="text" name="zhengxin_check_count_cycle" id="zhengxin_check_count_cycle_${countNum}"></div>
      <div class="zhengxin_popup_placeholder">月内查询</div>
      <div class="zhengxin_check_count_time_wrap"><input form='hidden_form_shaixuan' type="text" name="zhengxin_check_count_time" id="zhengxin_check_count_time_${countNum}"></div>
      <div class="click_to_delete" onclick='deleteThisFliterLine(this, event)'>-<img src="${imgURL}" alt="u1490"></div>
    </div>
    <script>
      $('#zhengxin_check_count_cycle_${countNum}').picker({
        title: "计算周期",
        cols: [
          {
            textAlign: 'center',
            values: window.zhengxinDataArray.mouthArray,
            displayValues: window.zhengxinDataArray.mouthViewArray
          }
        ],
        onChange: (picker, values, displayValues) => {
          picker.input.attr('inori-data-code', values[0])
          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
        }
      })
      $("#zhengxin_check_count_cycle_${countNum}").picker("open")
      $("#zhengxin_check_count_cycle_${countNum}").picker("close")
      $('#zhengxin_check_count_time_${countNum}').picker({
        title: "不超过",
        cols: [
          {
            textAlign: 'center',
            values: window.zhengxinDataArray.countTimeArray,
            displayValues: window.zhengxinDataArray.countTimeViewArray
          }
        ],
        onChange: (picker, values, displayValues) => {
          picker.input.attr('inori-data-code', values[0])
          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
        }
      })
      $("#zhengxin_check_count_time_${countNum}").picker("open")
      $("#zhengxin_check_count_time_${countNum}").picker("close")
    </script>
  `.trim()
  parentEle.closest('.weui_cells').append(templ)
})
// 动态添加逾期筛选条件
$('#click_to_add_yuqi').on('click', (evt) => {
  const parentEle = $(evt.target).closest('.fliter_line')
  const imgURL = parentEle.attr('imgurl')
  // 自增才能下一步
  const countNum = Number(parentEle.attr('inori-count')) + 1
  if (countNum > 7) {
    $.toptip(`每类条件最多可以添加7条`)
    throw new Error(`每类条件最多可以添加7条`)
  }
  parentEle.attr('inori-count', countNum)
  const templ = `
    <div class="fliter_line">
      <div class="yuqi_check_count_cycle_wrap"><input form='hidden_form_shaixuan' type="text" name="yuqi_check_count_cycle" id="yuqi_check_count_cycle_${countNum}"></div>
      <div class="yuqi_check_count_method_wrap">月内有<input form='hidden_form_shaixuan' type="text" name="yuqi_check_count_method" id="yuqi_check_count_method_${countNum}" value='累计' style="display:none;" readonly></div>
      <div class="yuqi_check_count_time_wrap"><input form='hidden_form_shaixuan' type="text" name="yuqi_check_count_time" id="yuqi_check_count_time_${countNum}"></div>
      <div class="yuqi_check_count_source_wrap"><input form='hidden_form_shaixuan' type="text" name="yuqi_check_count_source" id="yuqi_check_count_source_${countNum}"></div>
      <div class="click_to_delete" onclick='deleteThisFliterLine(this, event)'>-<img src="${imgURL}" alt="u1490"></div>
    </div>
    <script>
      $('#yuqi_check_count_cycle_${countNum}').picker({
        title: "N个月",
        cols: [
          {
            textAlign: 'center',
            values: window.zhengxinDataArray.yuqiCheckCountCycleArray,
            displayValues: window.zhengxinDataArray.yuqiCheckCountCycleViewArray
          }
        ],
        onChange: (picker, values, displayValues) => {
          picker.input.attr('inori-data-code', values[0])
          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
        }
      })
      $("#yuqi_check_count_cycle_${countNum}").picker("open")
      $("#yuqi_check_count_cycle_${countNum}").picker("close")

      $('#yuqi_check_count_time_${countNum}').picker({
        title: "N个",
        cols: [
          {
            textAlign: 'center',
            values: window.zhengxinDataArray.yuqiCheckCountTimeArray,
            displayValues: window.zhengxinDataArray.yuqiCheckCountTimeViewArray
          }
        ],
        onChange: (picker, values, displayValues) => {
          picker.input.attr('inori-data-code', values[0])
          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
        }
      })
      $("#yuqi_check_count_time_${countNum}").picker("open")
      $("#yuqi_check_count_time_${countNum}").picker("close")

      $('#yuqi_check_count_source_${countNum}').picker({
        title: "N",
        cols: [
          {
            textAlign: 'center',
            values: window.zhengxinDataArray.yuqiCheckCountSourceArray,
            displayValues: window.zhengxinDataArray.yuqiCheckCountSourceViewArray
          }
        ],
        onChange: (picker, values, displayValues) => {
          picker.input.attr('inori-data-code', values[0])
          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)
        }
      })
      $("#yuqi_check_count_source_${countNum}").picker("open")
      $("#yuqi_check_count_source_${countNum}").picker("close")
    </script>
  `.trim()
  parentEle.closest('.weui_cells').append(templ)
})

// 动态删除条件
function deleteThisFliterLine (_this, evt) {
  $(evt.target).closest('.fliter_line').remove()
}

// 添加渠道至聊天室

function AddPersonToRoom (_this, evt) {
  evt.stopPropagation()
  evt.preventDefault()
  // alert(`building test`)
  // $.toptip(`请先填写客户资料`, 'error')
  // throw new Error(`building`)
  const qudaoID = String($(evt.target).attr('qudao-id'))
  const ajaxIfURL = String($('#chat_ajax_cue').val())
  const ajaxAddURL = String($('#chat_add_chat_group').val())
  const roomID = String($('#chat_person_id').val())
  const goodsID = String($(evt.target).attr('goods-id'))
  const from_user_group_id = sessionStorage.getItem('from_user_group_id')
  if (from_user_group_id === null || from_user_group_id === 'null') {
    const flag = confirm(`发起联系前需要先完善客户资料，是否前往填写？`)
    if (flag) {
      sessionStorage.setItem('qudaoID', qudaoID)
      window.top.postMessage({jumpTo: 'data'}, '*')
    }

    throw new Error(`添加渠道失败，不存在聊天室`)
  }
  const ajaxIfData = {
    chat_id: roomID,
    goods_id: goodsID,
    y_id: qudaoID,
    from_user_group_id: from_user_group_id
  }
  const ajaxAddData = {
    chat_id: roomID,
    goods_id: goodsID,
    y_id: qudaoID
  }
  new Promise((resolve, reject) => {
    $.ajax(ajaxIfURL, {
      method: 'post',
      data: ajaxIfData,
      beforeSend: () => {
        $.toptip('正在查询聊天人员身份', 'success')
      }
    }).fail((err) => {
      $.toptip('添加渠道时失败', 'error')
      throw err
    }).done((res) => {
      if (String(res.code) !== '1') {
        $.toptip(`验证渠道身份异常，服务器返回：${res.message}`, 'warning')
        console.log(`验证渠道身份异常，服务器返回：${res.message}`)
        reject(new Error(`验证渠道身份异常，服务器返回：${res.message}`))
      } else {
        $.toptip('验证渠道身份请求发送成功', 'success')
        console.log('验证渠道身份请求发送成功')
        console.log(res)
        resolve()
      }
    })
  }).then((data) => {
    return new Promise((resolve, reject) => {
      $.ajax(ajaxAddURL, {
        method: 'post',
        data: ajaxAddData,
        beforeSend: () => {
          $.toptip('正在添加聊天人员。。', 'success')
        }
      }).fail((err) => {
        $.toptip('添加渠道时失败', 'error')
        reject(err)
        throw err
      }).done((res) => {
        if (String(res.code) === '5') {
          $.toptip('渠道人员已经存在', 'warning')
          console.log('渠道人员已经存在')
          $(evt.target).text('正在互动')
          $(evt.target).off('click')
          $(evt.target).on('click', (evt) => {
            $.toptip(`该渠道已经在留言板了`)
          })
          reject(new Error(`渠道人员已经存在`))
        } else if (String(res.code) !== '1') {
          $.toptip(`服务器反应异常: ${res.message}`, 'warning')
          console.log(`服务器反应异常: ${res.message}`)
          reject(new Error(`服务器反应异常: ${res.message}`))
        } else {
          $.toptip('添加渠道请求发送成功', 'success')
          console.log('添加渠道请求发送成功')
          console.log(res)
          resolve()
        }
      })
    })
  }).then((data) => {
    $.toptip('全部请求完毕', 'success')
    $(evt.target).text('正在互动')
    $(evt.target).removeAttr('onclick')
    $(evt.target).off('click')
    $(evt.target).on('click', (evt) => {
      $.toptip(`该渠道已经在留言板了`, 'warning')
      evt.preventDefault()
    })
    console.log('全部请求完毕')
    // 跳转
    window.top.postMessage({jumpTo: 'chat'}, '*')
  }).catch((err) => {
    if(err.message === '验证渠道身份异常，服务器返回：该用户对应该产品已经存在聊天室') {
      $(evt.target).text('正在互动')
      $(evt.target).removeAttr('onclick')
      $(evt.target).off('click')
      $(evt.target).on('click', (evt) => {
        $.toptip(`该渠道已经在留言板了`, 'warning')
        evt.preventDefault()
      })
    } else {
      evt.preventDefault()
    }
  })
}

// 修整渠道人员名字，过长就截取
// 2018年6月6日10点43分 应要求修改为 姓+经理 的格式,仅在按揭员视角显示全称
$('.sub_card_qudao_item .name').each((index, item) => {
  const anjie = `${$('#is_anjie').val()}` === '1'
  if (anjie && $(item).text().length > 4) $(item).text(`${$(item).text().substr(0,3)}...`)
  else if (!anjie) $(item).text(`${$(item).text().substr(0,1)}经理`)
})

// 可以取消选择
$('.tag_container label').on('click', (evt) => {
  if ($(evt.target).closest('.tag_container').children('input').prop('checked')) {
    // 已经选上了，要取消选择
    $(evt.target).closest('.tag_container').children('input').prop('checked', false)
    evt.stopPropagation()
    evt.preventDefault()
  }
})